package cn.dapeng.linked;

import cn.dapeng.utils.LinkedCreator;

/**
 * 双端链表反转
 */
public class ReverseDoubleLinkedNode {


    public static void main(String[] args) {
//        int testTimes = 1000000;
//        for (int i = 0; i < testTimes; i++) {
//            DoubleLinkedNode head = LinkedCreator.createDoubleLinkedNode(20, 10);
//
//            int length = LinkedCreator.getDoubleLinkedNodeLength(head);
//            check(head, length);
//        }
//        System.out.println("Over");

        DoubleLinkedNode head = LinkedCreator.createDoubleLinkedNode(20, 10);

        LinkedCreator.print2(head);
        head = reverse(head);
        LinkedCreator.print2(head);
    }

    public static DoubleLinkedNode reverse(DoubleLinkedNode head) {
        DoubleLinkedNode next = head, pre = null;

        while (head != null) {

            head = head.next;

            next.next = pre;
            next.pre = head;
            pre = next;
            next = head;
        }

        return pre;
    }


    /**
     * 双链表从头遍历到尾，在从尾遍历到头，检测是否是真正的双链表
     *
     * @param head
     */
    public static void check(DoubleLinkedNode head, int length) {

        int[] a = new int[length], b = new int[length];
        int index = 0;
        DoubleLinkedNode tail = head;
        while (tail != null) {
            a[index++] = tail.value;
            if (tail.next == null) {
                break;
            }
            tail = tail.next;
        }

        index = 0;
        while (tail != null) {
            b[index++] = tail.value;
            if (tail.pre == null) {
                break;
            }
            tail = tail.pre;
        }

        for (int i = 0; i < length; i++) {
            if (a[i] != b[length - 1 - i]) {
                System.out.println("Oops");
            }
        }
    }

}
